package net.kleinhenz.droidshop;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class ImageCache 
{
	public final static int THUMBNAIL = 0;
	public final static int FULL = 1;	
	
	private static Map<String, Drawable> cache = new HashMap<String, Drawable>();
	
	public static Drawable fetch(Context context, String urlString, int type) 
	{
		try
		{
			return ImageCache.fetch(context, new URL(urlString), type);
		}
		catch (MalformedURLException e)
		{
			return context.getResources().getDrawable(R.drawable.defaultproductimage);
		}
	}

	public static Drawable fetch(Context context, URL url, int type) 
	{
		if (type==THUMBNAIL && cache.containsKey(url.toString()))
			return cache.get(url.toString());
		
		File cachedFile = fileFromInputStream(context, url);
		Drawable drawable = null;
		if (cachedFile==null)
			drawable = context.getResources().getDrawable(R.drawable.defaultproductimage);				
		else
		{
			// drawable = Drawable.createFromPath(cachedFile.getAbsolutePath());
			try
			{
				InputStream bitmapInputStream = new FileInputStream(cachedFile);
				BitmapFactory.Options opts = new BitmapFactory.Options();
				if (type==THUMBNAIL)
					opts.inSampleSize = 5;
				else
					opts.inSampleSize = 1;
				Bitmap bitmap = BitmapFactory.decodeStream(bitmapInputStream, null,	opts);
				drawable = new BitmapDrawable(bitmap);
			}
			catch (FileNotFoundException e)
			{
				Log.e(DroidShop.APP_NAME, "Cached file not found for " + url.toString() + " file=" + cachedFile.getAbsolutePath());
				drawable = context.getResources().getDrawable(R.drawable.defaultproductimage);	
			}
		}
		
		if (type==THUMBNAIL && drawable!=null)
			cache.put(url.toString(), drawable);
		
		return drawable;
	}	

	private static File fileFromInputStream(Context context, URL url)
	{
		File cacheDir = context.getCacheDir();
		File tempFile = new File(cacheDir.getAbsolutePath() + "/" + url.toString().replace('/', '_') + ".img");
				
		if (!tempFile.exists() || !tempFile.canRead())
			try
			{
				InputStream is = (InputStream)url.getContent();
				FileOutputStream fos = new FileOutputStream(tempFile);
				int data = -1;
				while ((data=is.read())!=-1)
					fos.write(data);
				fos.close();
				is.close();
			}
			catch (IOException e)
			{
				Log.e(DroidShop.APP_NAME, "Error reading image from url " + url.toString());
				return null;
			}

		return tempFile;		
	}
}
